package com.dems.core.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.sql.*;

@Component
public class DbUtil {
    @Value("${spring.datasource2.driver-class-name:com.mysql.cj.jdbc.Driver}")
    private String driver;

    @Value("${spring.datasource2.url:jdbc:mysql://rm-bp1m4fy8d66u3c6xmbo.mysql.rds.aliyuncs.com:3306/cli_4513499?characterEncoding=utf-8&useSSL=false&useAffectedRows=true&serverTimezone=GMT%2B8}")
    private String connUrl;

    @Value("${spring.datasource2.userName:cli_4513499}")
    private String userName;

    @Value("${spring.datasource2.password:d7029e0d2eedb796}")
    private String password;

    @PostConstruct
    public void init() throws ClassNotFoundException {
        Class.forName(driver);
    }

    public Connection getConnection(){
        try {
            return DriverManager.getConnection(connUrl, userName, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public void close(Connection con, Statement preparedStatement, ResultSet resultSet){
                try {
                    if(con != null) {
                        con.close();
                    }
                    if(preparedStatement != null){
                        preparedStatement.close();
                    }
                    if(resultSet != null){
                        resultSet.close();
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }

    }

    public void close(Connection con, Statement preparedStatement){
        close(con, preparedStatement, null);
    }

    public void close(Connection con, ResultSet resultSet){
        close(con, null, resultSet);
    }
}
